import { message } from 'antd';
import dayjs from 'dayjs';

class Tools {
  /**
   * async function
   * @param fn function
   */
  static asyncFunc<T = void>(fn: () => T, delay: number = 0) {
    setTimeout(() => {
      fn();
    }, delay);
  }

  /**
   * getStorage
   * @param key
   * @returns
   */
  static getStorage(key: string) {
    return window.localStorage.getItem(key);
  }

  /**
   * setStorage
   * @param key
   * @param val
   */
  static setStorage(key: string, val: unknown) {
    let v = val;
    if (typeof val === 'object') {
      v = JSON.stringify(val);
    }
    window.localStorage.setItem(key, v as string);
  }

  /**
   * remove storage
   * @param key
   */
  static removeStorage(key: string) {
    window.localStorage.removeItem(key);
  }

  static errorMessage(error: any) {
    message.error(error.response.data.message || '发生未知错误');
  }

  static copyText(text: string) {
    navigator.clipboard.writeText(text);
  }

  static durationFormat(startTime: string, endTime: string) {
    let start = dayjs(startTime);
    let end = dayjs(endTime);
    let minutes = end.diff(start, 'minute');
    if (minutes < 60) return `${minutes}分钟`;
    let hours = end.diff(start, 'hour');
    if (hours < 24) return `${hours}小时`;
    let days = end.diff(start, 'day');
    hours = hours - days * 24;
    return hours > 0 ? `${days}天${hours}小时` : `${days}天`;
  }
}

export default Tools;
